package com.lsk.handler;

import com.alibaba.druid.support.http.StatViewServlet;
import com.jfinal.handler.Handler;
import com.jfinal.kit.HandlerKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.druid.IDruidStatViewAuth;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2018/9/4 0004.
 */
public class DruidStatViewHandlerRewrite extends Handler {
    private IDruidStatViewAuth auth;
    private String visitPath;
    private StatViewServlet servlet;

    public DruidStatViewHandlerRewrite(String visitPath) {
        this(visitPath, new IDruidStatViewAuth() {
            public boolean isPermitted(HttpServletRequest request) {
                String requestURI = request.getRequestURI();
                if (requestURI.contains(".js") || requestURI.contains(".css") || requestURI.contains("login.html")
                        || requestURI.contains("/submitLogin")){
                    return true;
                }else {
                    Object druidUser=request.getSession().getAttribute("druid-user");
                    return druidUser!=null;
                }
            }
        });
    }

    public DruidStatViewHandlerRewrite(String visitPath, IDruidStatViewAuth druidStatViewAuth) {
        this.visitPath = "/druid";
        this.servlet = new DruidStatViewHandlerRewrite.JFinalStatViewServlet();
        if(StrKit.isBlank(visitPath)) {
            throw new IllegalArgumentException("visitPath can not be blank");
        } else if(druidStatViewAuth == null) {
            throw new IllegalArgumentException("druidStatViewAuth can not be null");
        } else {
            visitPath = visitPath.trim();
            if(!visitPath.startsWith("/")) {
                visitPath = "/" + visitPath;
            }

            this.visitPath = visitPath;
            this.auth = druidStatViewAuth;
        }
    }

    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        if(target.startsWith(this.visitPath)) {
            isHandled[0] = true;
            String ctx = request.getContextPath();
            if(ctx != null && !"".equals(ctx) && !"/".equals(ctx)) {
                target = ctx + target;
            }

            if(target.equals(this.visitPath) && !target.endsWith("/index.html")) {
                HandlerKit.redirect(target + "/index.html", request, response, isHandled);
                return;
            }

            try {
                this.servlet.service(request, response);
            } catch (Exception var7) {
                throw new RuntimeException(var7);
            }
        } else {
            this.next.handle(target, request, response, isHandled);
        }

    }

class JFinalStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = 2898674199964021798L;
    private String username="lsk";
    private String password="Lishaokang.123";
    JFinalStatViewServlet() {
    }

    public boolean isPermittedRequest(HttpServletRequest request) {
        return DruidStatViewHandlerRewrite.this.auth.isPermitted(request);
    }

    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();
        response.setCharacterEncoding("utf-8");
        if (contextPath == null) {
            contextPath = "";
        }
        int index = contextPath.length() + DruidStatViewHandlerRewrite.this.visitPath.length();
        String uri = requestURI.substring(0, index);
        String path = requestURI.substring(index);
        if (!this.isPermittedRequest(request)) {
            path = "/nopermit.html";
            this.returnResourceFile(path, uri, response);
        } else {
            String fullUrl;
            if ("/submitLogin".equals(path)) {
                fullUrl = request.getParameter("loginUsername");

                String passwordParam = request.getParameter("loginPassword");
                if (this.username.equals(fullUrl) && this.password.equals(passwordParam)) {
                    request.getSession().setAttribute("druid-user", this.username);
                    response.getWriter().print("success");
                } else {
                    response.getWriter().print("error");
                }

            } else if (this.isRequireAuth() && !this.ContainsUser(request) && !"/login.html".equals(path) && !path.startsWith("/css") && !path.startsWith("/js") && !path.startsWith("/img")) {
                if (contextPath != null && !contextPath.equals("") && !contextPath.equals("/")) {
                    if ("".equals(path)) {
                        response.sendRedirect("druid/login.html");
                    } else {
                        response.sendRedirect("login.html");
                    }
                } else {
                    response.sendRedirect("/druid/login.html");
                }

            } else if (!"".equals(path)) {
                if ("/".equals(path)) {
                    response.sendRedirect("index.html");
                } else if (path.indexOf(".json") >= 0) {
                    fullUrl = path;
                    if (request.getQueryString() != null && request.getQueryString().length() > 0) {
                        fullUrl = path + "?" + request.getQueryString();
                    }

                    response.getWriter().print(this.process(fullUrl));
                } else {
                    this.returnResourceFile(path, uri, response);
                }
            } else {
                if (contextPath != null && !contextPath.equals("") && !contextPath.equals("/")) {
                    response.sendRedirect("druid/index.html");
                } else {
                    response.sendRedirect("/druid/index.html");
                }

            }
        }
    }
 }
}
